// https://github.com/facebook/react-native/issues/9599
if (typeof global.self === 'undefined') {
  global.self = global
}
import {
  AsyncStorage,
  Dimensions,
  Platform,
  PixelRatio,
  NetInfo,
} from 'react-native'

const AS_KEY = 'APP_TOKEN'
const APP_VERSION = '1.0.0'

const server = 'http://119.23.225.190/api/'
// const server = 'http://47.94.152.253:8080/api/'
// const server = 'http://192.168.199.180:8080/'
const deviceH = Dimensions.get('window').height
const deviceW = Dimensions.get('window').width

const basePx = 375

export const imageServer = 'http://119.23.225.190/files'
// export const imageServer = 'http://47.94.152.253:8080/files'

export { NavigationActions } from 'react-navigation'

export const delay = time => new Promise(resolve => setTimeout(resolve, time))

export const createAction = type => payload => ({ type, payload })

export function getVersion() {
  return APP_VERSION
}

export function px2dp(px) {
  return px * deviceW / basePx
}
export function getBorderWidth() {
  return (Platform.OS === 'ios' ? 1.0 : 1.0) / PixelRatio.get()
}
export function isIos() {
  return Platform.OS === 'ios'
}

export async function setAsyncStorage(key, value) {
  return new Promise((resolve, reject) => {
    AsyncStorage.setItem(key, value, error => {
      if (!error) {
        resolve(true)
      } else {
        resolve(false)
      }
    })
  })
}

export async function getAsyncStorage(key) {
  return new Promise((resolve, reject) => {
    AsyncStorage.getItem(key, (error, result) => {
      if (!error) {
        resolve(result)
      } else {
        reject()
      }
    })
  })
}
export async function removeAsyncStorage(key) {
  return new Promise((resolve, reject) => {
    AsyncStorage.removeItem(key, error => {
      if (!error) {
        resolve(true)
      } else {
        resolve(false)
      }
    })
  })
}
export async function isConnected() {
  return new Promise((resolve, reject) => {
    NetInfo.isConnected.fetch().done(isConnected => {
      if (isIos()) {
        resolve(true)
      } else {
        resolve(isConnected)
      }
    })
  })
}

export async function request({
  url,
  data,
  method = 'GET',
  net = false,
  token = true,
  timeout = 20000,
}) {
  const network = await isConnected()

  if (!network) {
    return new Promise((resolve, reject) => {
      if (net) {
        reject({ code: 300, msg: '请开启网络' })
      } else {
        reject({ code: 500, msg: '请开启网络' })
      }
    })
  }

  if (!data) {
    data = {}
  }
  if (token) {
    const accessToken = await getAsyncStorage(AS_KEY)
    if (accessToken) {
      const tokenJson = JSON.parse(accessToken)
      let tokenString = tokenJson.token
      const expire = tokenJson.expire
      // 如果快过期，刷新token
      if (expire - new Date().getTime() < 60 * 5) {
        tokenString = await refreshToken(tokenString)
      }
      data.token = tokenString
    } else {
      data.token = ''
    }
  }
  let params = ''
  if (data) {
    Object.keys(data).map((key, index) => {
      if (index == 0) {
        params += `${key}=${data[key]}`
      } else {
        params += `&${key}=${data[key]}`
      }
    })
  }

  url = server + url
  if (method.toLowerCase() == 'GET'.toLowerCase() && params != '') {
    if (url.indexOf('?') < 0) {
      url += '?'
    }
    url += params
  }
  const config = {
    method,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
  }
  if (method.toLowerCase() == 'POST'.toLowerCase()) {
    config.headers = {
      'Content-Type': 'application/x-www-form-urlencoded',
    }
    config.body = params
  }

  console.log(config, url)

  const promise = fetch(url, config)

  const abort_promise = new Promise((resolve, reject) => {
    setTimeout(() => {
      reject({ code: 500, msg: '网络请求超时' })
    }, timeout)
  })

  return new Promise((resolve, reject) => {
    Promise.race([promise, abort_promise])
      .then(response => {
        if (response.status != 200) {
          reject({ code: 401, msg: '未登录' })
        } else {
          return response.json()
        }
      })
      .then(data => {
        if (data.code) {
          reject(data)
        } else {
          resolve(data)
        }
      })
      .catch(error => {
        // reject('Error from cbAfter3s Sync 001');
        reject({ code: 500, msg: '网络请求失败' })
      })
  })
}

export function accAdd(arg1, arg2) {
  let r1, r2, m
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2))
  return (arg1 * m + arg2 * m) / m
}

export function accSub(arg1, arg2) {
  let r1, r2, m, n
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2))
  // last modify by deeka
  // 动态控制精度长度
  n = r1 >= r2 ? r1 : r2
  return ((arg1 * m - arg2 * m) / m).toFixed(n)
}

export function accMul(arg1, arg2) {
  let m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString()
  try {
    m += s1.split('.')[1].length
  } catch (e) {}
  try {
    m += s2.split('.')[1].length
  } catch (e) {}
  return (
    Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
  )
}
/*
export function accDiv(arg1, arg2) {
    var t1 = 0, t2 = 0, r1, r2;
    try {
        t1 = arg1.toString().split(".")[1].length;
    }
    catch (e) {
    }
    try {
        t2 = arg2.toString().split(".")[1].length;
    }
    catch (e) {
    }
    with (Math) {
        r1 = Number(arg1.toString().replace(".", ""));
        r2 = Number(arg2.toString().replace(".", ""));
        return (r1 / r2) * pow(10, t2 - t1);
    }
} */

export function getNowFormatDate() {
  const date = new Date()
  const seperator1 = '-'
  const seperator2 = ':'
  let month = date.getMonth() + 1
  let strDate = date.getDate()
  let hours=date.getHours()
  let minutes=date.getMinutes()
  let seconds=date.getSeconds()

  if (month >= 1 && month <= 9) {
    month = `0${month}`
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = `0${strDate}`
  }
  if (hours >= 0 && hours <= 9) {
    hours = `0${hours}`
  }
  if (minutes >= 0 && minutes <= 9) {
    minutes = `0${minutes}`
  }
  if (seconds >= 0 && seconds <= 9) {
    seconds = `0${seconds}`
  }
  const currentdate = `${date.getFullYear() +
    seperator1 +
    month +
    seperator1 +
    strDate} ${hours}${seperator2}${minutes}${seperator2}${seconds}`
  return currentdate
}
async function refreshToken(token) {
  const url = `${server}sys/user/refreshToken`
  const data = request({
    url,
    data: { token },
    method: 'get',
    token: false,
  })
  // 存储token
  setAsyncStorage(AS_KEY, JSON.stringify(data.data))
  return data.data.token
}
